///
<reference types="@dcloudio/types" />
<template>
  <view class="gift-container">
    <!-- 顶部剩余数量展示 -->
    <view class="remaining-card">
      <view class="title">当前剩余沐浴露</view>
      <view class="amount">{{ totalAmount }} 包</view>
      <view class="history-link" @tap="goToHistory">
        <text class="text">发放历史</text>
      </view>
    </view>

    <!-- 步骤1：选择赠送人 -->
    <view class="step-section">
      <view class="step-title">步骤1：选择赠送人</view>
      <view class="search-box">
        <input
          type="text"
          class="search-input"
          placeholder="请输入赠送人ID"
          v-model="recipientId"
          @confirm="handleSearch"
        />
        <view class="search-btn" @tap="handleSearch">
          <uni-icons type="search" size="20" color="#FFFFFF"></uni-icons>
        </view>
      </view>

      <!-- 搜索结果展示 -->
      <view class="user-card" v-if="selectedUser">
        <image
          class="avatar"
          :src="selectedUser.avatar || '/static/images/default-avatar.png'"
          mode="aspectFill"
        ></image>
        <view class="user-info">
          <text class="name">{{ selectedUser.name }}</text>
          <text class="id">ID{{ selectedUser.id }}</text>
        </view>
      </view>
    </view>

    <!-- 步骤2：设置赠送信息 -->
    <view class="step-section">
      <view class="step-title">步骤2：设置赠送信息</view>
      <view class="gift-input-box">
        <view class="input-row">
          <view class="input-label">赠送份数：</view>
          <input
            type="number"
            class="gift-input"
            v-model="giftCount"
            placeholder="请输入赠送份数"
          />
          <view class="input-unit">份</view>
        </view>
        <view class="input-row">
          <view class="input-label">每份数量：</view>
          <input
            type="number"
            class="gift-input"
            v-model="giftPerCount"
            placeholder="请输入每份数量"
          />
          <view class="input-unit">包</view>
        </view>
      </view>
    </view>

    <!-- 底部提示和确认按钮 -->
    <view class="confirm-section">
      <text class="warning-text">赠送后无法撤回，请确认信息无误</text>
      <button class="confirm-btn" @tap="handleConfirm" :disabled="!canSubmit">
        确认发放
      </button>
    </view>

    <!-- 加载中遮罩 -->
    <uni-popup ref="loadingPopup" type="center" :mask-click="false">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { sendGift, searchUser } from "../../api/gift";
import { getUserCoin } from "../../api/bgame";

// 类型定义
interface SelectedUser {
  id: number;
  name: string;
  avatar: string;
}

interface UniShowToastOptions {
  title: string;
  icon?: "success" | "loading" | "none";
  duration?: number;
}

interface UniShowModalOptions {
  title: string;
  content: string;
  success: (res: { confirm: boolean; cancel: boolean }) => void;
}

declare const uni: {
  showToast: (options: UniShowToastOptions) => void;
  showModal: (options: UniShowModalOptions) => void;
  navigateTo: (options: { url: string; success?: () => void }) => void;
  showLoading: (options: { title: string; mask?: boolean }) => void;
  hideLoading: () => void;
};

// 数据定义
const recipientId = ref("");
const giftCount = ref("");
const giftPerCount = ref("");
const totalAmount = ref(0);
const loadingPopup = ref();

// 选中的用户信息
const selectedUser = ref<SelectedUser | null>(null);

// 是否可以提交
const canSubmit = computed(() => {
  return (
    selectedUser.value &&
    Number(giftCount.value) > 0 &&
    Number(giftPerCount.value) > 0 &&
    totalNeedAmount.value <= totalAmount.value
  );
});

// 计算总需求量
const totalNeedAmount = computed(() => {
  const count = Number(giftCount.value) || 0;
  const perCount = Number(giftPerCount.value) || 0;
  return count * perCount;
});

// 获取剩余数量
const fetchRemaining = async () => {
  try {
    uni.showLoading({ title: "加载中" });
    const res = await getUserCoin({});
    if (res.result === 1 && res.data) {
      // 从数组中找到consume_type=7的记录
      const targetRecord = res.data.find((item) => item.consume_type === 7);
      totalAmount.value = targetRecord ? Number(targetRecord.num || 0) : 0;
    } else {
      totalAmount.value = 0;
    }
  } catch (error) {
    console.error("获取剩余数量失败:", error);
    totalAmount.value = 0;
  } finally {
    uni.hideLoading();
  }
};

// 搜索用户
const handleSearch = async () => {
  if (!recipientId.value) {
    uni.showToast({
      title: "请输入赠送人ID",
      icon: "none",
    });
    return;
  }

  try {
    loadingPopup.value.open();
    const res = await searchUser({ id: recipientId.value });
    if (res.result === 1 && res.data) {
      console.log(res.data);
      selectedUser.value = res.data;
    } else {
      uni.showToast({
        title: res.msg || "用户不存在",
        icon: "none",
      });
      selectedUser.value = null;
    }
  } catch (error) {
    console.error("搜索用户失败:", error);
    uni.showToast({
      title: "网络错误",
      icon: "none",
    });
  } finally {
    loadingPopup.value.close();
  }
};

// 跳转到历史记录
const goToHistory = () => {
  uni.navigateTo({
    url: "/subpages/gift/history",
    success: () => {
      // 页面跳转成功后，设置一个标记，表示需要刷新数据
      setTimeout(() => {
        fetchRemaining();
      }, 1000);
    },
  });
};

// 确认赠送
const handleConfirm = () => {
  if (!selectedUser.value) {
    uni.showToast({
      title: "请选择赠送人",
      icon: "none",
    });
    return;
  }

  const user = selectedUser.value; // 创建一个非空引用

  if (!giftCount.value || Number(giftCount.value) <= 0) {
    uni.showToast({
      title: "请输入正确的赠送份数",
      icon: "none",
    });
    return;
  }
  if (!giftPerCount.value || Number(giftPerCount.value) <= 0) {
    uni.showToast({
      title: "请输入正确的每份数量",
      icon: "none",
    });
    return;
  }

  // 验证剩余沐浴露是否足够
  if (totalNeedAmount.value > totalAmount.value) {
    uni.showToast({
      title: `剩余沐浴露不足，当前仅有${totalAmount.value}包`,
      icon: "none",
    });
    return;
  }

  uni.showModal({
    title: "确认赠送",
    content: `确定要赠送 ${giftCount.value} 份，每份 ${giftPerCount.value} 包沐浴露给 ${user.name} 吗？总共需要 ${totalNeedAmount.value} 包沐浴露。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          loadingPopup.value.open();
          const result = await sendGift({
            recipient_id: user.id,
            gift_count: Number(giftCount.value),
            gift_per_count: Number(giftPerCount.value),
          });

          if (result.result === 1) {
            uni.showToast({
              title: "赠送成功",
              icon: "success",
            });
            // 重置表单
            resetForm();
            // 刷新剩余数量
            fetchRemaining();
          } else {
            uni.showToast({
              title: result.msg || "赠送失败",
              icon: "none",
            });
          }
        } catch (error) {
          console.error("赠送礼包失败:", error);
          uni.showToast({
            title: "网络错误",
            icon: "none",
          });
        } finally {
          loadingPopup.value.close();
        }
      }
    },
  });
};

// 重置表单
const resetForm = () => {
  recipientId.value = "";
  giftCount.value = "";
  giftPerCount.value = "";
  selectedUser.value = null;
};

// 页面加载时获取剩余数量
// onMounted(() => {
//   fetchRemaining();
// });

// 页面显示时刷新数据
onShow(() => {
  fetchRemaining();
});
</script>

<style lang="scss" scoped>
.gift-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.remaining-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  position: relative;

  .title {
    font-size: 28rpx;
    color: #666666;
    margin-bottom: 10rpx;
  }

  .amount {
    font-size: 48rpx;
    font-weight: bold;
    color: #333333;
  }

  .history-link {
    position: absolute;
    top: 30rpx;
    right: 30rpx;

    .text {
      color: #00a971;
      font-size: 28rpx;
    }
  }
}

.step-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .step-title {
    font-size: 32rpx;
    color: #00a971;
    margin-bottom: 30rpx;
  }
}

.search-box {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .search-input {
    flex: 1;
    height: 80rpx;
    background: #f5f5f5;
    border-radius: 40rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
  }

  .search-btn {
    width: 80rpx;
    height: 80rpx;
    background: #00a971;
    border-radius: 40rpx;
    margin-left: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.user-card {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 12rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
  }

  .user-info {
    .name {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 6rpx;
      display: block;
    }

    .id {
      font-size: 24rpx;
      color: #999999;
    }
  }
}

.gift-input-box {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.input-row {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 0 20rpx;
  height: 80rpx;
}

.input-label {
  font-size: 28rpx;
  color: #333333;
  width: 160rpx;
}

.gift-input {
  flex: 1;
  height: 80rpx;
  background: transparent;
  border: none;
  font-size: 28rpx;
  color: #666666;
}

.input-unit {
  font-size: 28rpx;
  color: #999999;
  margin-left: 10rpx;
}

.total-need {
  margin-top: 20rpx;
  padding: 20rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  gap: 10rpx;

  .need-info {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #333333;
  }

  .need-label {
    margin-right: 10rpx;
  }

  .need-amount {
    font-weight: bold;
    color: #00a971;

    &.insufficient {
      color: #ff0000;
    }
  }

  .status-text {
    font-size: 24rpx;
    color: #999999;
    text-align: center;
    display: block;
  }

  .error-text {
    color: #ff0000;
  }

  .success-text {
    color: #00a971;
  }
}

.confirm-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-top: 40rpx;

  .warning-text {
    font-size: 24rpx;
    color: #999999;
    text-align: center;
    display: block;
    margin-bottom: 20rpx;
  }

  .confirm-btn {
    background: #00a971;
    color: #ffffff;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;

    &[disabled] {
      background: #cccccc;
      color: #ffffff;
    }
  }
}

.loading-content {
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 2px solid #ffffff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.loading-text {
  color: #ffffff;
  font-size: 14px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
